<!--
 * @Descripttion: 创建一个 ws 客户端
 * @version: 1.0
 * @Author: 自由如风
 * @Date: 2021-05-22 16:40:15
 * @LastEditors: 自由如风
 * @LastEditTime: 2021-05-22 20:42:13
-->
<template>
  <div class="client">
    <h4>{{ speed }} 条/分钟</h4>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [],
    };
  },
  async created() {
    const params = new URLSearchParams(location.search);
    const openId = params.get("openId");
    if (!openId) {
      alert("身份有误，请重新扫描二维码进入 ^;^ ");
      location.reload();
    }
    try {
      await this.$store.dispatch("initsystem");
      await this.$store.dispatch("initstore", openId);
    } catch (e) {
      alert("请求服务器失败");
      location.reload();
    }

    const url = new URL(location.origin);
    url.protocol = "ws:";
    url.port = this.system.wssport;

    console.log(url, this.$store.state.system);

    const wsclient = new WebSocket(url);

    wsclient.onopen = function (event) {
      console.log("已连接至服务器", event);
      wsclient.send(openId);
    };

    wsclient.onclose = function (event) {
      alert("与服务连接断开");
      location.reload();
    };

    wsclient.onmessage = this.switchMessage;

    // wsclient.send(openId);
  },
  methods: {
    /** 处理收到的消息 */
    switchMessage(event) {
      try {
        const data = JSON.parse(event.data);
        data.time = Date.now();
        this.list.push(data);
        switch (data.type) {
          case "barrage":
            this.sendBarrage(data.data);
        }
      } catch (e) {
        console.error(`处理消息失败`, e, event);
      }
    },
    /** 发送弹幕 data:收到服务器的消息，那别send啥，这边接受啥 */
    sendBarrage(data) {
      console.log(data);
      this.$parent.$refs.barragecontainer.add(data);
    },
  },
  computed: {
    system() {
      return this.$store.state.system;
    },
    speed() {
      //   this.list = this.list.filter((e) => e.time < Date.now + 3600 * 1000);
      return this.list.filter((e) => e.time > Date.now() - 60 * 1000).length;
    },
  },
};
</script>

<style scoped>
.client {
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgb(66, 66, 66);
  border-bottom-right-radius: 1em;
  padding: 0.5em;
  color: white;
  font-weight: bold;
}
</style>